package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    UserDao userDao;

    @Autowired
    RoleDao roleDao;

    //根据用户权限展示页面信息
    @Override
    public List<Map<String,Object>> ShowMenuByUserRole(String username) {
        //根据用户名查询出用户对象
        User user = userDao.findUserByUsername(username);

        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findRolesByUserId(user.getId());

        //创建要返回的菜单集合
        List<Map<String,Object>> list = new ArrayList<>();

        for (Role role : roles) {
            LinkedHashSet<Menu> menus = role.getMenus();
            for (Menu menu : menus) {
                if(menu.getParentMenuId() == null){
                Map map = new HashMap();
                String name = menu.getName();
                String path = menu.getPath();
                String linkUrl = menu.getLinkUrl();
                String icon = menu.getIcon();
                List<Menu> children = menu.getChildren();

                //封装子菜单信息
                List<Map<String,Object>> childList = new ArrayList<>();
                //遍历子菜单数据,将前端需要的数据封装到Map集合,再将Map集合放入List当中
                for (Menu child : children) {
                    Map map2 = new HashMap();
                    String childName = child.getName();
                    String childPath = child.getPath();
                    String childLinkUrl = child.getLinkUrl();
                    List<Menu> childChildren = child.getChildren();
                    map2.put("title",childName);
                    map2.put("path",childPath);
                    map2.put("linkUrl",childLinkUrl);
                    map2.put("children",childChildren);
                    childList.add(map2);
                }
                map.put("title",name);
                map.put("path",path);
                map.put("linkUrl",linkUrl);
                map.put("icon",icon);
                map.put("children",childList);
                list.add(map);
                }
            }
        }
        return list;
    }
}
